package com.example.cm_player.activity

import android.os.Bundle
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.example.cm_base.BaseActivity
import com.example.cm_player.model.SongInfo
import com.example.cm_design.MusicProgressBar
import com.example.cm_player.model.PlayMode
import com.example.cm_player.R
import com.example.cm_player.MusicListDialog
import com.example.cm_player.databinding.ActivityPlayerBinding
import com.example.cm_player.manager.PlayerManager
import com.example.cm_player.manager.PlayerStateManager
import com.example.cm_utils.TimeFormatter


/**
 * 音乐播放器界面
 */
class PlayerActivity : BaseActivity<ActivityPlayerBinding, PlayerViewModel>() {
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        viewModel.bindPlayerService()

        initView()
        initClickListener()
        initProgressBar()
    }

    private fun initView() {
        // 获取当前歌曲信息
        val currentSong = PlayerStateManager.currentPlayedMusic.value

        // 更新UI显示
        binding.btnPlayMode.setImageResource(
            when (PlayerManager.getInstance().getPlayMode()) {
                PlayMode.LIST_LOOP -> R.drawable.ic_repeat_list
                PlayMode.SINGLE_LOOP -> R.drawable.ic_repeat_one
                PlayMode.RANDOM -> R.drawable.ic_shuffle
            }
        )

        // 更新专辑封面
        updateAlbumCover(currentSong)

        // 更新歌曲信息
        updateSongInfo(currentSong)

        // 更新播放状态
        updatePlayPauseButton(PlayerStateManager.isPlaying.value == true)

        // 更新收藏状态
        updateFavoriteButton(currentSong?.isFavorite == true)

        // 使用TimeFormatter格式化时间显示
        binding.tvProgress.text = TimeFormatter.formatTime(PlayerStateManager.currentProgress.value)
        binding.tvDuration.text = TimeFormatter.formatTime(PlayerStateManager.duration.value)
    }


    /**
     * 更新专辑封面
     */
    private fun updateAlbumCover(songInfo: SongInfo?) {
        // 更新专辑封面
        Glide.with(this)
            .load(songInfo?.imageUrl)
            .error(R.drawable.ic_music_default)
            .into(binding.ivAlbum)

        // 更新背景（使用虚化的专辑封面）
        Glide.with(this)
            .load(songInfo?.imageUrl)
            .error(R.drawable.ic_music_default)
            .into(binding.ivBackground)
    }

    /**
     * 更新歌曲信息
     */
    private fun updateSongInfo(songInfo: SongInfo?) {
        binding.tvSongTitle.text = songInfo?.title ?: "未知歌曲"
        binding.tvArtist.text = songInfo?.artist ?: "未知艺术家"
        binding.tvAlbumName.text = songInfo?.album ?: "未知专辑"
    }

    /**
     * 更新播放/暂停按钮
     */
    private fun updatePlayPauseButton(isPlaying: Boolean) {
        binding.btnPlayPause.setImageResource(
            if (isPlaying) R.drawable.ic_media_pause else R.drawable.ic_media_play
        )
    }

    /**
     * 更新收藏按钮
     */
    private fun updateFavoriteButton(isFavorite: Boolean) {
        binding.btnFavorite.setImageResource(
            if (isFavorite) R.drawable.ic_favorite_filled else R.drawable.ic_favorite_border
        )
    }

    /**
     * 初始化进度条控件
     */
    private fun initProgressBar() {
        // 设置进度条的初始值
        updateProgressBar(
            PlayerStateManager.currentProgress.value ?: 0,
            PlayerStateManager.duration.value ?: 100
        )

        // 设置进度条的拖动监听
        binding.progressBar.setOnProgressChangeListener(object :
            MusicProgressBar.OnProgressChangeListener {
            override fun onProgressChanged(progress: Float, fromUser: Boolean) {
                if (fromUser) {
                    val duration = PlayerStateManager.duration.value ?: 0
                    val targetPosition = (progress / 100f * duration).toLong()
                    viewModel.seekTo(progress)
                    binding.tvProgress.text = TimeFormatter.formatTime(targetPosition)
                }
            }
        })
    }

    override fun initObservers() {
        PlayerStateManager.currentPlayedMusic.observe(this, Observer { songInfo ->
            // 当歌曲变化时，更新UI
            updateAlbumCover(songInfo)
            updateSongInfo(songInfo)
            updateFavoriteButton(songInfo!!.isFavorite)
        })

        // 观察当前播放进度
        PlayerStateManager.currentProgress.observe(this, Observer { progress ->
            binding.tvProgress.text = TimeFormatter.formatTime(progress)
            val duration = PlayerStateManager.duration.value ?: 100
            updateProgressBar(progress, duration)
        })

        PlayerStateManager.duration.observe(this, Observer { duration ->
            binding.tvDuration.text = TimeFormatter.formatTime(duration)
            val progress = PlayerStateManager.currentProgress.value ?: 0
            updateProgressBar(progress, duration)
        })

        PlayerStateManager.isPlaying.observe(this, Observer { isPlaying ->
            updatePlayPauseButton(isPlaying)
        })

        PlayerStateManager.currentPlayMode.observe(this, Observer { playMode ->
            if (playMode != null) {
                binding.btnPlayMode.setImageResource(
                    when (playMode) {
                        PlayMode.LIST_LOOP -> R.drawable.ic_repeat_list
                        PlayMode.SINGLE_LOOP -> R.drawable.ic_repeat_one
                        PlayMode.RANDOM -> R.drawable.ic_shuffle
                    }
                )
            }
        })
    }

    /**
     * 更新进度条显示
     */
    private fun updateProgressBar(currentMs: Long, totalMs: Long) {
        if (totalMs <= 0) return

        // 计算进度百分比
        val progressPercent = (currentMs.toFloat() / totalMs) * 100

        // 更新进度条
        binding.progressBar.setProgress(progressPercent)
    }

    private fun initClickListener() {
        // 播放/暂停按钮点击事件
        binding.btnPlayPause.setOnClickListener {
            if (PlayerStateManager.isPlaying.value == true) {
                viewModel.pause()
            } else {
                viewModel.start()
            }
        }

        binding.btnPrevious.setOnClickListener {
            viewModel.previousMusic()
        }

        binding.btnNext.setOnClickListener {
            viewModel.nextMusic()
        }

        binding.btnPlayMode.setOnClickListener {
            switchPlayMode()
        }

        binding.btnSongList.setOnClickListener {
            MusicListDialog().apply {
                removeMusicCallback = {
                    viewModel.removeFromPlaylist(it)
                }
                changeMusicCallback = {
                    viewModel.playSong(it)
                }
                show(supportFragmentManager, null)
            }
        }

        binding.btnFavorite.setOnClickListener {
            val currentSong =
                PlayerStateManager.currentPlayedMusic.value ?: return@setOnClickListener
            // 切换收藏状态
            currentSong.isFavorite = !currentSong.isFavorite
            // 更新UI
            updateFavoriteButton(currentSong.isFavorite)
        }

        binding.ivBack.setOnClickListener {
            finish()
        }
    }

    /**
     * 切换播放模式
     */
    private fun switchPlayMode() {
        val currentMode = PlayerManager.getInstance().getPlayMode()
        val newMode = when (currentMode) {
            PlayMode.LIST_LOOP -> PlayMode.SINGLE_LOOP
            PlayMode.SINGLE_LOOP -> PlayMode.RANDOM
            PlayMode.RANDOM -> PlayMode.LIST_LOOP
        }
        viewModel.setPlayMode(newMode)
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.unbindPlayerService()
    }
} 